import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select, DatePicker, InputNumber, Switch, Space, Button, TimePicker, Checkbox, Radio } from 'antd';
import moment from 'moment';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { request } from 'umi';

const { Option } = Select;
const { TextArea } = Input;
const TimeRangePicker = TimePicker.RangePicker;

// 获取门店列表
const fetchStores = async (params) => {
  return request('/api/v1/store', {
    method: 'GET',
    params: { ...params, pageSize: 999 },
  });
};

// 获取场地列表
const fetchVenues = async (params) => {
  return request('/api/v1/venue', {
    method: 'GET',
    params: { ...params, pageSize: 999 },
  });
};

const ActivityForm = ({ visible, onCancel, onOk, form, formTitle, coupons, loading, initialValues }) => {
  const [stores, setStores] = useState([]);
  const [venues, setVenues] = useState([]);
  const [applicableType, setApplicableType] = useState(0);

  const fetchStoreAndVenueData = async () => {
    const storeRes = await fetchStores({});
    if (storeRes.success) {
      setStores(storeRes.data.list || []);
    }
    const venueRes = await fetchVenues({});
    if (venueRes.success) {
      setVenues(venueRes.data.list || []);
    }
  };

  useEffect(() => {
    if (visible) {
      fetchStoreAndVenueData();
    }
  }, [visible]);

  useEffect(() => {
    if (visible) {
      if (initialValues) {
        // 编辑模式：设置表单值
        setApplicableType(initialValues.applicable_type || 0);
        let available_times = [];
        try {
          available_times = initialValues.available_times
            ? JSON.parse(initialValues.available_times).map((timeRange) => [
                moment(timeRange?.start, 'HH:mm'),
                moment(timeRange?.end, 'HH:mm'),
              ])
            : [];
        } catch (e) {
          console.log('解析可用时段失败:', e);
        }

        const transformedValues = {
          ...initialValues,
          start_time: moment.unix(initialValues.start_time),
          end_time: moment.unix(initialValues.end_time),
          available_times: available_times,
          available_weekdays: initialValues.available_weekdays
            ? JSON.parse(initialValues.available_weekdays)
            : [],
          applicable_ids: initialValues.applicable_ids
            ? JSON.parse(initialValues.applicable_ids)
            : [],
          status: initialValues.status === 1,
        };
        form.setFieldsValue(transformedValues);
      } else {
        // 创建模式：重置并设置默认值
        form.resetFields();
        setApplicableType(0);
        form.setFieldsValue({
          type: 0,
          status: true,
          start_time: moment(),
          end_time: moment().add(30, 'days'),
          applicable_type: 0,
        });
      }
    }
  }, [visible, initialValues, form]);

  const handleOk = () => {
    form.validateFields().then((values) => {
      const transformedValues = {
        ...values,
        start_time: values.start_time.unix(),
        end_time: values.end_time.unix(),
        available_times: JSON.stringify(
          values.available_times
            ? values.available_times.map((item) => ({
                start_time: item[0].format('HH:mm'),
                end_time: item[1].format('HH:mm'),
              }))
            : []
        ),
        available_weekdays: JSON.stringify(values.available_weekdays || []),
        applicable_ids: JSON.stringify(values.applicable_ids || []),
        status: values.status ? 1 : 0,
      };
      onOk(transformedValues);
    });
  };

  return (
    <Modal
      title={formTitle}
      visible={visible}
      onCancel={onCancel}
      footer={[
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" loading={loading} onClick={handleOk}>
          确定
        </Button>,
      ]}
      width={700}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
      >
        <Form.Item
          name="name"
          label="活动名称"
          rules={[{ required: true, message: '请输入活动名称' }]}
        >
          <Input placeholder="请输入活动名称" />
        </Form.Item>

        <Form.Item
          name="type"
          label="活动类型"
          rules={[{ required: true, message: '请选择活动类型' }]}
        >
          <Select placeholder="请选择活动类型">
            <Option value={0}>折扣</Option>
            <Option value={1}>满减</Option>
            <Option value={2}>满赠</Option>
            <Option value={3}>送优惠券</Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="description"
          label="活动描述"
        >
          <TextArea rows={4} placeholder="请输入活动描述" />
        </Form.Item>

        <Form.Item label="活动时间" style={{ marginBottom: 0 }}>
          <Space style={{ display: 'flex', width: '100%' }}>
            <Form.Item
              name="start_time"
              rules={[{ required: true, message: '请选择开始时间' }]}
              style={{ marginBottom: 0, flex: 1 }}
            >
              <DatePicker
                showTime
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="开始时间"
                style={{ width: '100%' }}
              />
            </Form.Item>
            <Form.Item
              name="end_time"
              rules={[{ required: true, message: '请选择结束时间' }]}
              style={{ marginBottom: 0, flex: 1 }}
            >
              <DatePicker
                showTime
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="结束时间"
                style={{ width: '100%' }}
              />
            </Form.Item>
          </Space>
        </Form.Item>

        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}
        >
          {({ getFieldValue }) => {
            const type = getFieldValue('type');
            if (type === 1) { // 满减
              return (
                <>
                  <Form.Item
                    name="min_amount"
                    label="最低消费金额(元)"
                    rules={[{ required: true, message: '请输入最低消费金额' }]}
                  >
                    <InputNumber
                      min={0}
                      precision={2}
                      style={{ width: '100%' }}
                      placeholder="请输入最低消费金额"
                    />
                  </Form.Item>
                  <Form.Item
                    name="discount_rate"
                    label="优惠金额(元)"
                    rules={[{ required: true, message: '请输入优惠金额' }]}
                  >
                    <InputNumber
                      min={0}
                      precision={2}
                      style={{ width: '100%' }}
                      placeholder="请输入优惠金额"
                    />
                  </Form.Item>
                </>
              );
            }
            if (type === 0) { // 折扣
              return (
                <>
                  <Form.Item
                    name="discount_rate"
                    label="折扣率(0-10)"
                    rules={[{ required: true, message: '请输入折扣率' }]}
                  >
                    <InputNumber
                      min={0}
                      max={10}
                      precision={1}
                      style={{ width: '100%' }}
                      placeholder="请输入折扣率，如8.5表示8.5折"
                    />
                  </Form.Item>
                  <Form.Item
                    name="min_amount"
                    label="最低消费金额(元)"
                  >
                    <InputNumber
                      min={0}
                      precision={2}
                      style={{ width: '100%' }}
                      placeholder="请输入最低消费金额，不填表示无限制"
                    />
                  </Form.Item>
                </>
              );
            }
            if (type === 3) { // 优惠券
              return (
                <Form.Item
                  name="coupon_ids"
                  label="关联优惠券"
                  rules={[{ required: true, message: '请选择关联优惠券' }]}
                >
                  <Select
                    mode="multiple"
                    placeholder="请选择关联优惠券"
                    style={{ width: '100%' }}
                  >
                    {coupons && coupons.map(coupon => (
                      <Option key={coupon.id} value={coupon.id}>{coupon.name}</Option>
                    ))}
                  </Select>
                </Form.Item>
              );
            }
            return null;
          }}
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          valuePropName="checked"
        >
          <Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked />
        </Form.Item>

        <Form.Item
          name="applicable_type"
          label="适用范围"
          initialValue={0}
        >
          <Radio.Group onChange={(e) => setApplicableType(e.target.value)}>
            <Radio value={0}>全场通用</Radio>
            <Radio value={1}>指定门店</Radio>
            <Radio value={2}>指定包厢</Radio>
          </Radio.Group>
        </Form.Item>

        {applicableType === 1 && (
          <Form.Item
            name="applicable_ids"
            label="选择门店"
            rules={[{ required: true, message: '请选择适用的门店' }]}
          >
            <Select
              mode="multiple"
              placeholder="请选择门店"
              style={{ width: '100%' }}
              filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {stores.map(store => (
                <Option key={store.id} value={store.id}>{store.name}</Option>
              ))}
            </Select>
          </Form.Item>
        )}

        {applicableType === 2 && (
          <Form.Item
            name="applicable_ids"
            label="选择包厢"
            rules={[{ required: true, message: '请选择适用的包厢' }]}
          >
            <Select
              mode="multiple"
              placeholder="请选择包厢"
              style={{ width: '100%' }}
              filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {venues.map(venue => (
                <Option key={venue.id} value={venue.id}>{venue.name}</Option>
              ))}
            </Select>
          </Form.Item>
        )}

        <Form.Item name="available_weekdays" label="可用星期">
          <Checkbox.Group
            options={[
              { label: '周一', value: '1' },
              { label: '周二', value: '2' },
              { label: '周三', value: '3' },
              { label: '周四', value: '4' },
              { label: '周五', value: '5' },
              { label: '周六', value: '6' },
              { label: '周日', value: '0' },
            ]}
          />
        </Form.Item>

        <Form.List name="available_times">
          {(fields, { add, remove }) => (
            <>
              {fields.map((field, index) => (
                <Form.Item
                  label={index === 0 ? '可用时段' : ''}
                  required={false}
                  key={field.key}
                >
                  <Space>
                    <Form.Item
                      {...field}
                      rules={[
                        {
                          required: true,
                          message: '请选择时间范围',
                        },
                      ]}
                      noStyle
                    >
                      <TimeRangePicker format="HH:mm" />
                    </Form.Item>
                    <MinusCircleOutlined
                      onClick={() => remove(field.name)}
                    />
                  </Space>
                </Form.Item>
              ))}
              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => add()}
                  style={{ width: '100%' }}
                  icon={<PlusOutlined />}
                >
                  添加时间段
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List>
      </Form>
    </Modal>
  );
};

export default ActivityForm;